import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { SYSTEM_PERMISSIONS, MONITOR_PERMISSIONS } from '@/config/permissions'

// 配置NProgress
NProgress.configure({ showSpinner: false })

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/shared/login/index.vue'),
    meta: {
      title: '登录',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/modules/dashboard/index.vue'),
        meta: {
          title: '仪表盘',
          icon: 'Odometer',
          requiresAuth: true
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/modules/profile/index.vue'),
        meta: {
          title: '个人中心',
          icon: 'User',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/system',
    name: 'System',
    component: () => import('@/layout/index.vue'),
    meta: {
      title: '系统管理',
      icon: 'Setting',
      requiresAuth: true
    },
    children: [
      {
        path: 'user',
        name: 'SystemUser',
        component: () => import('@/views/modules/system/user/index.vue'),
        meta: {
          title: '用户管理',
          icon: 'User',
          requiresAuth: true,
          permissions: [SYSTEM_PERMISSIONS.USER_LIST]
        }
      },
      {
        path: 'role',
        name: 'SystemRole',
        component: () => import('@/views/modules/system/role/index.vue'),
        meta: {
          title: '角色管理',
          icon: 'UserFilled',
          requiresAuth: true,
          permissions: [SYSTEM_PERMISSIONS.ROLE_LIST]
        }
      },
      {
        path: 'menu',
        name: 'SystemMenu',
        component: () => import('@/views/modules/system/menu/index.vue'),
        meta: {
          title: '菜单管理',
          icon: 'Menu',
          requiresAuth: true,
          permissions: [SYSTEM_PERMISSIONS.MENU_LIST]
        }
      },
      {
        path: 'dept',
        name: 'SystemDept',
        component: () => import('@/views/modules/system/dept/index.vue'),
        meta: {
          title: '部门管理',
          icon: 'OfficeBuilding',
          requiresAuth: true,
          permissions: [SYSTEM_PERMISSIONS.DEPT_LIST]
        }
      },
      {
        path: 'settings',
        name: 'SystemSettings',
        component: () => import('@/views/modules/settings/index.vue'),
        meta: {
          title: '系统设置',
          icon: 'Setting',
          requiresAuth: true,
          permissions: [SYSTEM_PERMISSIONS.SETTINGS_VIEW]
        }
      }
    ]
  },
  {
    path: '/monitor',
    name: 'Monitor',
    component: () => import('@/layout/index.vue'),
    meta: {
      title: '系统监控',
      icon: 'Monitor',
      requiresAuth: true
    },
    children: [
      {
        path: 'online',
        name: 'MonitorOnline',
        component: () => import('@/views/modules/monitor/online/index.vue'),
        meta: {
          title: '在线用户',
          icon: 'User',
          requiresAuth: true,
          permissions: [MONITOR_PERMISSIONS.ONLINE_LIST]
        }
      },
      {
        path: 'loginlog',
        name: 'MonitorLoginLog',
        component: () => import('@/views/modules/monitor/loginlog/index.vue'),
        meta: {
          title: '登录日志',
          icon: 'Document',
          requiresAuth: true,
          permissions: [MONITOR_PERMISSIONS.LOGINLOG_LIST]
        }
      },
      {
        path: 'operlog',
        name: 'MonitorOperLog',
        component: () => import('@/views/modules/monitor/operlog/index.vue'),
        meta: {
          title: '操作日志',
          icon: 'Document',
          requiresAuth: true,
          permissions: [MONITOR_PERMISSIONS.OPERLOG_LIST]
        }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/shared/error/404.vue'),
    meta: {
      title: '页面不存在',
      hideInMenu: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  
  const userStore = useUserStore()
  const appStore = useAppStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - Convallaria`
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    const token = getToken()
    
    if (!token) {
      // 未登录，跳转到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 已登录，检查用户信息
    if (!userStore.userInfo) {
      try {
        await userStore.getUserInfo()
        await appStore.getMenuList()
      } catch (error) {
        // 获取用户信息失败，清除token并跳转登录
        userStore.logout()
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
        return
      }
    }
    
    // 检查权限
    if (to.meta.permissions && !userStore.hasPermission(to.meta.permissions as string[])) {
      ElMessage.error('权限不足')
      next('/404')
      return
    }
  }
  
  next()
})

// 全局后置钩子
router.afterEach(() => {
  NProgress.done()
})

export default router
